package servidor.principal.control;


import comun.iControl.*;
import comun.dto.*;

import java.rmi.server.UnicastRemoteObject;
import java.util.*; 

import servidor.dominio.Cliente;
import servidor.dominio.LibroIva;
import servidor.dominio.Comprobante;
import servidor.principal.assembler.*;


import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Extent;
import javax.jdo.Query;
import javax.jdo.JDOHelper;
import javax.jdo.Transaction;
import servidor.dominio.*; 



public class ControlLibroIva extends UnicastRemoteObject implements IControlLibroIva{


    public ControlLibroIva() throws Exception{   }

    public void delLibroIvaDTO(LibroIvaDTO libIvaDTO) throws Exception {
    }

    public boolean addLibroIvaDTO(LibroIvaDTO libIvaDTO,String nombreCliente) throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx=pm.currentTransaction();
        try{ 
        	tx.begin();
        	//Recupero el cliente al cual hace referencia el libro de iva
        	String filter = "nombre == \""+nombreCliente+"\"";
 	        Cliente cliente = (Cliente)this.getObject(pm, Cliente.class, filter);
		    LibroIvaAssembler libroIvaAssembler = new LibroIvaAssembler();
		    LibroIva libroIva= libroIvaAssembler.getLibroIva(libIvaDTO);
		    libroIva.setCliente(cliente);       
		    libIvaDTO=libroIvaAssembler.getLibroIvaDTO(libroIva);    			 
		    pm.makePersistent(libroIva);
		    tx.commit();
		    System.out.println("Libro de iva dado de alta. OK");    			
    		}
    		finally
            {
                if (tx.isActive())
                {
                    tx.rollback();
                }
                pm.close();
            }                
    	return true;
    	}
    

    public Vector<ComprobanteDTO> getComprobantes() throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
     	PersistenceManager pm = pmf.getPersistenceManager();
     	Transaction tx=pm.currentTransaction();
         tx = pm.currentTransaction();         
         Vector<ComprobanteDTO> vector = new Vector <ComprobanteDTO>();
         Collection<Comprobante> consultaCol = null;       
         
         try {
             if (!tx.isActive())tx.begin();
             consultaCol= this.getObjects(pm,Comprobante.class);
             Iterator<Comprobante> iter = consultaCol.iterator();
             while (iter.hasNext()) {
            	 Comprobante comp = iter.next();
            	 ComprobanteDTO compDTO = ComprobanteAssembler.getComprobanteDTO(comp);
             	vector.add(compDTO);
             }            
             tx.commit();
         } catch (RuntimeException e) {
         	e.printStackTrace();
         } finally {
         	if (tx.isActive()) tx.rollback();
         }
         return vector;
    }

    public boolean existeLibroIva(String mes) throws Exception {
    	
        PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
        tx = pm.currentTransaction();
        
        boolean existe = false;
        try {
       
            if (!tx.isActive())tx.begin();
            String filter = "mes == \""+mes+"\"";
            Collection LibroIvaCol= this.getObjects(pm,LibroIva.class,filter);
            if (LibroIvaCol.size()>=1) 
                existe=true;

    try {
                tx.commit(); 
            } catch (RuntimeException e) {
                e.printStackTrace();
                return false;
            }
        } finally {
        
        
        if (tx.isActive()) tx.rollback();
        }
        return existe;
    
    	
     } 
        

     public LibroIvaDTO buscarLibroIvaDTO(String mes) throws Exception {
    	 PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
     	 PersistenceManager pm = pmf.getPersistenceManager();
     	 Transaction tx=pm.currentTransaction();
         tx = pm.currentTransaction();
         LibroIvaDTO libIvaDTO= new LibroIvaDTO();
         LibroIva libIva= new LibroIva();
         try {
             if (!tx.isActive())tx.begin();
             String filter = "mes == \""+mes+"\"";
             libIva= (LibroIva) this.getObject(pm,LibroIva.class,filter);
             LibroIvaAssembler libIvaAssembler = new LibroIvaAssembler();
             libIvaDTO=libIvaAssembler.getLibroIvaDTO(libIva);
                  try {
                 tx.commit(); 
             } catch (RuntimeException e) {
                 e.printStackTrace();
              
             }
         } finally {
         
         
         if (tx.isActive()) tx.rollback();
         }
         return libIvaDTO;
    }
     
     public Collection getObjects(PersistenceManager pm, Class clase,String filter)throws Exception{
     	Collection retorno=null;
     	try{
             Class clienteClass = clase;
             Extent clnCliente = pm.getExtent(clienteClass, false);
             Query query = pm.newQuery(clnCliente,filter);
             retorno=(Collection)query.execute();
     	} catch(Exception e) {
             throw e;
     	}
     	return retorno;
     }
    
    public Object getObject(PersistenceManager pm,Class clase,String filter) throws Exception{
    	Object objetoPersistente = null;
        try {
	        
        	Extent clnObject = pm.getExtent(clase, true);
	        Query query = pm.newQuery(clnObject,filter);
	        Collection objetos = (Collection)query.execute();
	        
	        
	        Object[] prueba = objetos.toArray();
	        if(prueba.length > 0){
	            	objetoPersistente = prueba[0];
	        }	
	    }
        catch (Exception ex) {
        	ex.printStackTrace();
            throw ex;           
        }
        return objetoPersistente;
    }
    
    
	private Collection getObjects(PersistenceManager pm, Class clase)throws Exception{
    	Collection retorno=null;
    	try{
            Class libroIvaClass = clase;
            Extent clnLibroIva = pm.getExtent(libroIvaClass, false);
            Query query = pm.newQuery(clnLibroIva);
            retorno=(Collection)query.execute();
    	} catch(Exception e) {
            throw e;
    	}
    	return retorno;
    }
	
	public void eliminarLibroIva(String mes) throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx=pm.currentTransaction();
        try {        	
		 	tx.begin();
		    if (!tx.isActive())tx.begin();   
		    LibroIva libroIva = new LibroIva();
		    String filter = "mes == \""+mes+"\"";
		    libroIva = (LibroIva)this.getObject(pm, LibroIva.class, filter);
		    
		    //Eliminamos los comprobantes que estan relacionados con el libro de iva
		    Collection comprobantes= this.getObjects(pm,Comprobante.class);
		    Iterator <Comprobante> it=comprobantes.iterator();
		    while (it.hasNext()){
		    	Comprobante comp= it.next();
		    	if (comp.getLibroIva().getId()==libroIva.getId()){
		    		pm.deletePersistent(comp);
		    	}		    	
		    }
		    //Ahora si eliminamos el libro de iva
           	pm.deletePersistent(libroIva);
            tx.commit(); 
    		System.out.println("Libro de iva Eliminado. OK");
        }	
		finally
		{
          if (tx.isActive())
          {
              tx.rollback();
          }
          pm.close();
		} 
	}
	
	public LibroIvaDTO getLibroIvaDTO(String cuit,String mes,String anio) throws Exception {	
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
        tx = pm.currentTransaction();
        LibroIvaDTO libIvaDTO= new LibroIvaDTO();
        LibroIva libIva= new LibroIva();
        try {
            if (!tx.isActive())tx.begin();
            String filter = "cuit ==\""+cuit+"\"";
            Cliente cliente = (Cliente)this.getObject(pm, Cliente.class, filter);            
            filter = "mes ==\""+mes+"\" && anio ==\""+anio+"\"";
            Collection libIvas=  this.getObjects(pm,LibroIva.class,filter);
            Iterator it = libIvas.iterator();
            while (it.hasNext()){
            	libIva = (LibroIva) it.next();
            	if (libIva.getCliente().getId()==cliente.getId()){
            		break;
            	}
            }
            System.out.println("libroIva:"+libIva.getId());
            System.out.println("Hay : "+libIva.getComprobantes().size());
            Thread.sleep(3000);
            LibroIvaAssembler libIvaAssembler = new LibroIvaAssembler();
            libIvaDTO=libIvaAssembler.getLibroIvaDTO(libIva);
                 try {
                tx.commit(); 
            } catch (RuntimeException e) {
                e.printStackTrace();
             
            }
        } finally {
        
        
        if (tx.isActive()) tx.rollback();
        }
        return libIvaDTO;
	    	}

	
	 public LibroIvaDTO getLibroIvaDTO(ClienteDTO clienteDTO,String mes,String anio) throws Exception {	
		 PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
	        PersistenceManager pm = pmf.getPersistenceManager();
	        Transaction tx=pm.currentTransaction();
	        LibroIvaDTO libroIvaDTO=null;
	        try{ 
	        	tx.begin();
	        	System.out.println(clienteDTO.getCuit());
	        	String filter ="mes == \""+mes+"\" && anio=="+anio +" && cliente.getCuit()=="+clienteDTO.getCuit() +"";
	        	Collection librosIva = this.getObjects(pm,LibroIva.class, filter);
	        	Iterator<LibroIva> it = librosIva.iterator();
	        	LibroIva libroIva=null;
	        	System.out.println(librosIva.size());
	        	boolean cond = true;
	        	while (it.hasNext()&& cond){
	        		libroIva = it.next();
	        		//System.out.println(libroIva.getMes());
	        		//System.out.println(libroIva.getId());
	        		
	        		libroIvaDTO= LibroIvaAssembler.getLibroIvaDTO(libroIva);
	        	//	System.out.println(libroIvaDTO.getMes());
	        		//System.out.println(libroIvaDTO.getId());
	        		//System.out.println(libroIvaDTO.getCliente().getId());
	        		if (libroIva.getCliente().getId() == clienteDTO.getId()){
	        			cond=false;
	        		}
	        	}
	        	
			    tx.commit();
			    	
	    		}
	    		finally
	            {
	                if (tx.isActive())
	                {
	                    tx.rollback();
	                }
	                pm.close();
	            }                
	    	return libroIvaDTO;
	    	}


}
